package com.shinhye.mobilelottery.net;

import java.io.InputStream;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.net.Proxy;

import com.shinhye.mobilelottery.ConstantValue;
import com.shinhye.mobilelottery.GlobalParams;

public class HttpClientUtils {
	private HttpClient client;

	public HttpClientUtils() {
		client = new DefaultHttpClient();
		//如果是wap方式，设置代理。
		if(GlobalParams.isWap) {
			String ip = Proxy.getDefaultHost();
			int port = Proxy.getDefaultPort();
			HttpHost host = new HttpHost(ip, port);
			client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, host);
		}
	}
	
	/**
	 * Send a xml String to server
	 * @param url The url of server 
	 * @param xml What xml to send to server
	 * @return InputStream that server return. If there is error, return null.
	 */
	public InputStream sendXml(String url, String xml) {
		HttpPost post = new HttpPost(url);
		try {
			StringEntity entity = new StringEntity(xml, ConstantValue.ENCODING);
			post.setEntity(entity);
			HttpResponse response = client.execute(post);
			if(response.getStatusLine().getStatusCode() == 200) {
				return response.getEntity().getContent();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
}
